package leetcode;

/**
 * 1432. 改变一个整数能得到的最大差值
 *
 * 小心replace的用法，如果rarget为空字符串，会将每个字符与字符串首尾都会添加上replacement字符串
 */
public class T1132TheMaximumDifferenceThatCanBeObtainedByChangingAnInteger {

    public static void main(String[] args) {

        T1132TheMaximumDifferenceThatCanBeObtainedByChangingAnInteger service = new T1132TheMaximumDifferenceThatCanBeObtainedByChangingAnInteger();

        service.maxDiff(9);
    }

    public int maxDiff(int num) {
        return maxNumber(num) - minNumber(num);
    }

    /**
     * 首位非1 将数变成1
     *      为1  将后置位第一个非0非1的数变成 0
     * @param num
     * @return
     */
    private int minNumber(int num) {
        int minNumber = num;
        String s = String.valueOf(num);
        String oldChar = "###";
        String newChar = "0";
        if(s.startsWith("1")){
            for(int i = 1 ;i<s.length();i++){
                Character c = s.charAt(i);
                if("0".equals(String.valueOf(c))||"1".equals(String.valueOf(c))){
                    continue;
                }
                oldChar = String.valueOf(c);
                newChar = "0";
                break;
            }
        }else{
            oldChar = s.substring(0, 1);
            newChar = "1";
        }
        String newNumber = s.replace(oldChar, newChar);
        minNumber = Integer.valueOf(newNumber);
        return minNumber;
    }

    /**
     * 找到非9 的变成9
     * @param num
     * @return
     */
    private int maxNumber(int num) {
        int maxNumber = num;
        String s = String.valueOf(num);
        String oldChar = "###";
        String newChar = "9";
        for(int i = 0 ;i<s.length();i++){
            Character c = s.charAt(i);
            if("9".equals(String.valueOf(c))){
                continue;
            }
            oldChar = String.valueOf(c);
            break;
        }
        String newNumber = s.replace(oldChar, newChar);
        maxNumber = Integer.valueOf(newNumber);
        return maxNumber;
    }
}
